package de.tum.beilmeiner.im.client.controller;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.rpc.server.RPC;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.novanic.eventservice.client.event.Event;
import de.novanic.eventservice.client.event.RemoteEventService;
import de.novanic.eventservice.client.event.RemoteEventServiceFactory;
import de.novanic.eventservice.client.event.listener.RemoteEventListener;
import de.tum.beilmeiner.im.client.InstantChat;
import de.tum.beilmeiner.im.client.MessagingService;
import de.tum.beilmeiner.im.client.MessagingServiceAsync;
import de.tum.beilmeiner.im.client.UserSessionHandler;

import de.tum.beilmeiner.im.client.event.LogoutEvent;
import de.tum.beilmeiner.im.client.view.LogoutWindow;


public class LogoutWindowController implements ClickHandler, RemoteEventListener {

	private UserSessionHandler userhandler = null;
	private LogoutWindow logoutWindow = null;
	private InstantChat mainWindow = null;
	private MessagingServiceAsync messagingService = null;

	public LogoutWindowController(LogoutWindow logoutWindow, UserSessionHandler userhandler, InstantChat mainWindow) {
		this.userhandler = userhandler;
		this.logoutWindow = logoutWindow;
		this.mainWindow = mainWindow;
		System.out.println(this);
		RemoteEventServiceFactory theEventServiceFactory = RemoteEventServiceFactory.getInstance();
		final RemoteEventService theEventService = theEventServiceFactory.getRemoteEventService();
		theEventService.addListener(userhandler.getLoginUser().getUserDomain(), this);
		logoutWindow.addLoginButtonListener(this);
		messagingService = GWT.create(MessagingService.class);
		
		
	}

	@Override
	public void onClick(ClickEvent event) {
		
		System.out.println("LogoutWindowController: "+userhandler.getLoginUser().getName() + " send logout ..");
		messagingService.sendLogoutRequest(userhandler.getLoginUser().getUserDomain(), userhandler.getLoginUser(), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);
				
			}

			@Override
			public void onSuccess(Void result) {
				System.out.println("send logout successful..");
				
			}
		});
	}

	@Override
	public void apply(Event anEvent) {

		if(anEvent instanceof LogoutEvent)
			onMyEvent((LogoutEvent)anEvent);

		
	}

	private void onMyEvent(LogoutEvent event) {
		System.out.println("logoutController received logout for user"+event.getUser().getName());
		userhandler.setLoginUser(null);
		mainWindow.switchToLogoutView();
			
	}

}
